﻿using ImageUploader;
using System;
using System.Configuration;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace Common
{
    class tempMethod2
    {
        private static byte[] _buffer = new byte[102400];
        private static int _receiveCount = 0;
        private static string _receiveString = string.Empty;
        private static ListBox listB;
        public static void SendToServer(string file, string path)
        {
            using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                try
                {
                    string ip = ConfigurationSettings.AppSettings["Server"].ToString();
                    int port = Convert.ToInt32(ConfigurationSettings.AppSettings["Port"].ToString());
                    IPEndPoint ep = new IPEndPoint(IPAddress.Parse(ip), port);
                    socket.Connect(ep);
                    ShowMsg.showMsg(listB, "连接成功...");
                    var bpp = new BreakPointPost(file, path);
                    string debug = string.Format("send argument:/r/nFileName|{0}|;Size|{1}|;PackageSize|{2}|;PackageCount|{3}|;Index|{4}|;", bpp.FileName, bpp.FileSize, bpp.PackageSize, bpp.PackageCount, bpp.Index);
                    socket.Send(Encoding.UTF8.GetBytes("send argument"));
                    Thread.Sleep(500);
                    socket.Send(Encoding.UTF8.GetBytes("FileName|" + bpp.FileName));
                    Thread.Sleep(500);
                    socket.Send(Encoding.UTF8.GetBytes("FileSize|" + bpp.FileSize));
                    Thread.Sleep(500);
                    socket.Send(Encoding.UTF8.GetBytes("PackageSize|" + bpp.PackageSize));
                    Thread.Sleep(500);
                    socket.Send(Encoding.UTF8.GetBytes("PackageCount|" + bpp.PackageCount));
                    Thread.Sleep(500);
                    socket.Send(Encoding.UTF8.GetBytes("Index|" + bpp.Index));
                    Thread.Sleep(500);
                    ShowMsg.showMsg(listB, debug);
                    socket.Send(Encoding.UTF8.GetBytes("start"));//告诉服务器，从这开始，我要开始发送文件了
                    ShowMsg.showMsg(listB, "start...");
                    while (true)
                    {
                        _buffer = FileRead(bpp.FilePath, bpp.Index, bpp.PackageSize);
                        socket.Send(_buffer, 0, _buffer.Length, SocketFlags.None);
                        var bufferLength = _buffer.Length;
                        Thread.Sleep(100);
                        _receiveCount = socket.Receive(_buffer);
                        _receiveString = Encoding.UTF8.GetString(_buffer, 0, _receiveCount);
                        if (_receiveString.Contains("success") && _receiveString.Split('|')[1] == bpp.Index.ToString())
                        {
                            bpp.Index++;
                            ShowMsg.showMsg(listB, string.Format("index is {0}/{1}({2})", bpp.Index, bpp.PackageCount, bufferLength));
                            if (bpp.Index == bpp.PackageCount) break;
                        }
                        else
                        {
                            Thread.Sleep(100);
                            continue;
                        }

                    }
                    ShowMsg.showMsg(listB, "finish");
                }
                catch (Exception ex)
                {
                    ShowMsg.showMsg(listB, ex.Message);
                }
                finally
                {
                    socket.Close();
                }
            }

        }

        private static int GetFilePackageCount(long fileSize, long packageSize)
        {
            int count = 0;
            if (fileSize % packageSize > 0)
                count = Convert.ToInt32(fileSize / packageSize) + 1;
            else
                count = Convert.ToInt32(fileSize / packageSize);
            return count;
        }
        private static byte[] FileRead(string path, int index, long size)
        {
            byte[] result = null;
            long length = (long)index * (long)size + size;
            using (FileStream stream = File.OpenRead(path))
            {
                if (length > stream.Length)
                    result = new byte[stream.Length - ((long)index * (long)size)];
                else
                    result = new byte[size];
                stream.Seek((long)index * (long)size, SeekOrigin.Begin);
                stream.Read(result, 0, result.Length);
            }
            return result;
        }

        public class BreakPointPost
        {
            public string FileName { get; set; }
            public string FilePath { get; set; }
            public long FileSize { get; set; }
            public long PackageSize { get; set; }
            public int PackageCount { get; set; }
            public int Index { get; set; }

            public BreakPointPost(string file, string path)
            {
                FileName = file;
                //FilePath = Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(System.Environment.CurrentDirectory)), FileName);
                FilePath = path;
                FileSize = new FileInfo(FilePath).Length;
                PackageSize = 102400;
                PackageCount = GetFilePackageCount(FileSize, PackageSize);
                Index = 0;
            }
        }
    }
}
